<template>
  <view class="ocr-container">
      <!-- 顶部标题 -->
      <view class="header">
        <text class="title">图片文字识别</text>
      </view>
    
    <!-- 使用说明 -->
    <view class="instruction-section">
      <text class="instruction-text">1. 点击上传图片按钮，选择需要识别的图片</text>
      <text class="instruction-text">2. 点击识别文字按钮，系统将提取图片中的文字</text>
      <text class="instruction-text">3. 识别完成后，可复制单条或全部文字</text>
    </view>
    
    <!-- 图片上传区域 -->
    <view class="upload-section">
      <view class="upload-btn" @click="chooseImage">
        <uni-icons type="image" size="40" color="#999999"></uni-icons>
        <text class="upload-text">点击上传图片</text>
      </view>
      
      <!-- 预览图片 -->
      <view class="image-preview" v-if="imagePath">
        <image :src="imagePath" mode="aspectFit"></image>
        <view class="image-action">
          <view class="action-btn" @click="chooseImage">
            <text>重新上传</text>
          </view>
          <view class="action-btn primary" @click="recognizeText">
            <text>识别文字</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-mask" v-if="isRecognizing">
      <view class="loading-content">
        <uni-load-more :status="'loading'" :content-text="{contentdown:'',contentrefresh:'正在识别...',contentup:''}"></uni-load-more>
      </view>
    </view>
    
    <!-- 识别结果区域 -->
    <view class="result-section" v-if="recognitionResults.length > 0">
      <view class="result-header">
        <text class="result-title">识别结果</text>
        <view class="result-actions">
          <view class="action-btn small" @click="copyAllText">
            <text>复制全部</text>
          </view>
          <view class="action-btn small primary" @click="clearResults">
            <text>清空</text>
          </view>
        </view>
      </view>
      
      <!-- 识别结果列表 -->
      <view class="result-list">
        <view class="result-item" v-for="(item, index) in recognitionResults" :key="index">
          <text class="result-text">{{ item.text }}</text>
          <view class="item-action">
            <view class="action-icon" @click="copyText(item.text)">
              <uni-icons type="copy" size="16" color="#999999"></uni-icons>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
  import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import uniLoadMore from '@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue'
  
  export default {
    components: {
      uniIcons,
      uniLoadMore
    },
    data() {
      return {
        imagePath: '', // 上传的图片路径
        isRecognizing: false, // 是否正在识别
        recognitionResults: [] // 识别结果列表
      }
    },
    onLoad() {
    },
    methods: {
      // 选择图片
      chooseImage() {
        const _this = this
        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: function(res) {
            _this.imagePath = res.tempFilePaths[0]
            _this.recognitionResults = [] // 清空之前的识别结果
          },
          fail: function(err) {
            console.error('选择图片失败:', err)
          }
        })
      },
      
      // 识别图片文字
      recognizeText() {
        if (!this.imagePath) {
          uni.showToast({
            title: '请先上传图片',
            icon: 'none'
          })
          return
        }
        
        this.isRecognizing = true
        
        // 将图片转换为base64格式
        this.getImageBase64(this.imagePath).then(base64 => {
          // 调用OCR接口进行识别
          return this.callOCRAPI(base64)
        }).then(results => {
          // 处理识别结果
          this.processRecognitionResults(results)
          this.isRecognizing = false
        }).catch(err => {
          console.error('识别失败:', err)
          uni.showToast({
            title: '识别失败，请重试',
            icon: 'none'
          })
          this.isRecognizing = false
        })
      },
      
      // 将图片转换为base64
      getImageBase64(imagePath) {
        return new Promise((resolve, reject) => {
          uni.getFileSystemManager().readFile({
            filePath: imagePath,
            encoding: 'base64',
            success: res => {
              resolve(res.data)
            },
            fail: err => {
              reject(err)
            }
          })
        })
      },
      
      // 调用OCR API
      callOCRAPI(base64Image) {
        return new Promise((resolve, reject) => {
          // 注意：这里使用的是模拟数据，实际项目中需要替换为真实的OCR服务
          // 以下提供了几种常用OCR服务的集成方式示例
          
          // 模拟OCR识别过程
          setTimeout(() => {
            // 这里应该是真实API返回的结果格式
            // 以下为模拟数据
            const mockResults = {
              words_result: [
                { words: '这是一段示例文字' },
                { words: '用于演示图片文字识别功能' },
                { words: '请替换为真实的OCR服务' },
                { words: '提取出的文字会显示在这里' }
              ]
            }
            resolve(mockResults)
          }, 2000)
        })
      },
      
      // 以下是实际集成OCR服务的示例方法（未使用）
      // 1. 百度OCR示例
      async callBaiduOCR(base64Image) {
        try {
          // 1. 先获取百度OCR的access_token
          const tokenResult = await this.getBaiduAccessToken()
          
          // 2. 调用百度OCR API
          const result = await uni.request({
            url: `https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=${tokenResult.access_token}`,
            method: 'POST',
            header: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: {
              image: base64Image
            }
          })
          
          return result.data
        } catch (error) {
          throw new Error('百度OCR识别失败')
        }
      },
      
      // 获取百度OCR的access_token
      getBaiduAccessToken() {
        return new Promise((resolve, reject) => {
          // 需要替换为实际的API Key和Secret Key
          const clientId = 'your_api_key' // 百度云应用的API Key
          const clientSecret = 'your_secret_key' // 百度云应用的Secret Key
          
          uni.request({
            url: `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}`,
            method: 'POST',
            success: (res) => {
              resolve(res.data)
            },
            fail: (err) => {
              reject(err)
            }
          })
        })
      },
      
      // 2. 阿里云OCR示例
      async callAliyunOCR(base64Image) {
        try {
          // 阿里云OCR需要进行签名验证，这里仅作简化示例
          // 实际使用时需要按照阿里云文档进行签名
          const result = await uni.request({
            url: 'https://ocrapi-ugc.taobao.com/ocrservice/ugc',
            method: 'POST',
            header: {
              'Content-Type': 'application/json',
              'Authorization': 'your_aliyun_authorization' // 阿里云授权信息
            },
            data: {
              image: base64Image,
              configure: '{"side":"face"}'
            }
          })
          
          return result.data
        } catch (error) {
          throw new Error('阿里云OCR识别失败')
        }
      },
      
      // 处理识别结果
      processRecognitionResults(results) {
        // 根据实际API返回格式调整
        if (results && results.words_result) {
          this.recognitionResults = results.words_result.map(item => ({
            text: item.words || item.text || item
          }))
        } else if (Array.isArray(results)) {
          this.recognitionResults = results.map(item => ({
            text: item
          }))
        }
        
        if (this.recognitionResults.length === 0) {
          uni.showToast({
            title: '未识别到文字',
            icon: 'none'
          })
        }
      },
      
      // 复制单条文本
      copyText(text) {
        uni.setClipboardData({
          data: text,
          success: () => {
            uni.showToast({
              title: '复制成功',
              icon: 'success'
            })
          }
        })
      },
      
      // 复制全部文本
      copyAllText() {
        const allText = this.recognitionResults.map(item => item.text).join('\n')
        this.copyText(allText)
      },
      
      // 清空结果
      clearResults() {
        this.recognitionResults = []
      }
    }
  }
</script>

<style scoped>
  .ocr-container {
    width: 100%;
    min-height: 100vh;
    background-color: #f8f8f8;
    padding-bottom: 20px;
  }
  
  /* 顶部标题 */
  .header {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #ffffff;
    border-bottom: 1px solid #eeeeee;
  }
  
  .title {
    font-size: 18px;
    font-weight: 500;
    color: #333333;
  }
  
  /* 图片上传区域 */
  .upload-section {
    padding: 20px;
    background-color: #ffffff;
    margin-top: 10px;
  }
  
  .upload-btn {
    width: 100%;
    height: 200px;
    border: 2px dashed #dddddd;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fafafa;
  }
  
  .upload-text {
    margin-top: 10px;
    font-size: 14px;
    color: #999999;
  }
  
  /* 图片预览 */
  .image-preview {
    width: 100%;
    border-radius: 8px;
    overflow: hidden;
    background-color: #fafafa;
  }
  
  .image-preview image {
    width: 100%;
    height: 200px;
  }
  
  .image-action {
    display: flex;
    justify-content: space-around;
    padding: 15px 0;
  }
  
  /* 加载状态 */
  .loading-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  
  .loading-content {
    background-color: #ffffff;
    padding: 20px;
    border-radius: 8px;
  }
  
  /* 结果区域 */
  .result-section {
    margin: 10px;
    background-color: #ffffff;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .result-header {
    padding: 15px;
    border-bottom: 1px solid #eeeeee;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .result-title {
    font-size: 16px;
    font-weight: 500;
    color: #333333;
  }
  
  .result-actions {
    display: flex;
    gap: 10px;
  }
  
  /* 按钮样式 */
  .action-btn {
    padding: 6px 16px;
    border-radius: 4px;
    background-color: #f0f0f0;
    font-size: 14px;
    color: #666666;
  }
  
  .action-btn.primary {
    background-color: #1989fa;
    color: #ffffff;
  }
  
  .action-btn.small {
    padding: 4px 12px;
    font-size: 12px;
  }
  
  /* 结果列表 */
  .result-list {
    max-height: 400px;
    overflow-y: auto;
  }
  
  .result-item {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }
  
  .result-item:last-child {
    border-bottom: none;
  }
  
  .result-text {
    flex: 1;
    font-size: 14px;
    color: #333333;
    line-height: 1.6;
  }
  
  .item-action {
    margin-left: 10px;
  }
  
  .action-icon {
    padding: 4px;
  }
    
    /* 使用说明 */
    .instruction-section {
      padding: 15px 20px;
      background-color: #ffffff;
      margin-top: 10px;
    }
    
    .instruction-text {
      display: block;
      font-size: 13px;
      color: #666666;
      margin-bottom: 6px;
      line-height: 1.5;
    }
</style>
